<template>
  <div id="container">
    <el-row :gutter="20">
      <el-col
        :xs="24"
        :sm="24"
        :md="8"
        :lg="6"
        :xl="5"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div style="text-align: center">
            <img
              :src="user.avatar"
              title="点击上传头像"
              class="avatar"
              @click="toggleShow"
            />
            <!--组件主体-->
            <my-upload
              field="img"
              :modelValue.sync="show"
              @crop-success="cropSuccess"
              @crop-upload-success="cropUploadSuccess"
              @crop-upload-fail="cropUploadFail"
              :headers="headers"
              input-of-file="file"
              method="GET"
              v-model="show"
              :width="400"
              :height="200"
              img-format="jpg"
              :url="updateAvatarApi"
              :size="size"
            ></my-upload>
            <img :src="avatar" />
          </div>
          <ul class="user-info">
            <li>
              <svg-icon icon-class="login" /> 登录账号
              <div class="user-right">{{ user.username }}</div>
            </li>
            <li>
              <div style="height: 100%">
                <svg-icon icon-class="user1" /> 管理角色
                <div class="user-right">{{ role.name }}</div>
              </div>
            </li>
            <li>
              <div style="height: 100%">
                <svg-icon icon-class="gender2" /> 用户性别
                <div class="user-right">男</div>
              </div>
            </li>
          </ul>
          <!-- <div v-for="o in 4" :key="o" class="text item">
            {{ "列表内容 " + o }}
          </div> -->
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="19">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>修改信息</span>
          </div>
          <el-form
            ref="form"
            :model="form"
            style="margin-top: 10px"
            size="small"
            label-width="65px"
          >
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex" style="width: 178px">
                <el-radio label="1">男</el-radio>
                <el-radio label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="">
              <el-button
                :loading="saveLoading"
                size="mini"
                type="primary"
                @click="doSubmit"
                >保存配置</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import store from "@/store";
import "babel-polyfill";
import myUpload from "vue-image-crop-upload";
import { mapGetters } from "vuex";
import { editUserInfo, editUserAvatar } from "@/api/common";
import Config from "@/settings";
import COS from "cos-js-sdk-v5";
import { v4 as uuidv4 } from "uuid";
import { getToken } from "@/utils/auth";
export default {
  name: "UserInfo",
  data() {
    return {
      //   user: store.getters.user,
      role: store.getters.role,
      form: {},
      avatarForm: {},
      saveLoading: false,
      avatar: "", //用于存储剪切完图片的base64Data和显示回调图片
      show: false, //剪切框显示和隐藏的flag
      size: 2.1,
      imgDataUrl: "", // the datebase64 url of created image
      file: null,
      headers: {
        token: getToken(),
      },
    };
  },
  //注册组件
  components: {
    "my-upload": myUpload,
  },
  computed: {
    ...mapGetters(["user", "updateAvatarApi"]),
  },
  created() {
    this.form = { id: this.user.id, sex: this.user.sex };
    this.avatarForm = { id: this.user.id, avatar: this.user.avatar };
  },
  methods: {
    //控制剪切框的显示和隐藏
    toggleShow() {
      this.show = !this.show;
    },
    /* //剪切成功后的回调函数
    cropSuccess(imgDataUrl) {
      //  imgDataUrl其实就是图片的base64data码
      this.avatar = imgDataUrl;
      console.log(imgDataUrl); //这里打印出来的是base64格式的资源
    }, */
    doSubmit() {
      console.log(this.form);
      this.saveLoading = true;
      editUserInfo(this.form)
        .then(() => {
          store.dispatch("getUserInfo").then(() => {});
          this.$notify({
            title: "成功",
            message: "成功修改性别！",
            type: "success",
          });
          this.saveLoading = false;
        })
        .catch(() => {
          this.$notify({
            title: "失败",
            message: "修改性别失败！",
            type: "error",
          });
          this.saveLoading = false;
        });
    },
    // vue-image-crop-upload

    /**
     * crop success
     * 将截取成功的图片转为base64进而发送到对象存储
     *
     * [param] imgDataUrl
     * [param] field
     */
    //剪切成功后的回调函数
    //  imgDataUrl其实就是图片的base64data码
    cropSuccess(imgDataUrl, field) {
      var arr = imgDataUrl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      this.file = new Blob([u8arr], { type: mime });
      console.log(field);
      // console.log(imgDataUrl);
      console.log("-------- crop success --------");
      this.imgDataUrl = imgDataUrl;
    },
    /**
     * upload success
     *
     * [param] jsonData   服务器返回数据，已进行json转码
     * [param] field
     */
    cropUploadSuccess(res, field) {
      //FIXME: 插件配置和对象存储糅杂一起
      console.log(res);
      const cos = new COS({
        // getAuthorization 必选参数
        getAuthorization: function (options, callback) {
          console.log(res.data);
          const credentials = res.data.credentials;
          console.log(credentials.tmpSecretId);
          callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            SecurityToken: credentials.sessionToken,
            StartTime: res.data.startTime,
            ExpiredTime: res.data.expiredTime,
          });
        },
      });
      var that = this;
      cos.putObject(
        {
          Bucket: Config.Bucket /* 填入您自己的存储桶，必须字段 */,
          Region: Config.Region /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key:
            "image/" +
            uuidv4() /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: this.file,
        },
        function (err, data) {
          // 获取图片上传到COS的返回对象（包括URL地址）
          console.log("===-------------======", err || data);
          if (err) {
            // 上传到云存储失败了
            that.$notify.error({
              title: "错误",
              message: "修改头像失败！",
            });
          } else {
            // this.avatarForm.avatar = "http://" + data.Location;
            console.log(that);
            that.$set(that.avatarForm, "avatar", "http://" + data.Location);
            console.log(that.avatarForm);
            editUserAvatar(that.avatarForm)
              .then(() => {
                store.dispatch("getUserInfo").then(() => {});
                that.$notify({
                  title: "成功",
                  message: "成功修改头像！",
                  type: "success",
                });
              })
              .catch(() => {
                // 云存储地址传给后端失败了
                that.$notify.error({
                  title: "错误",
                  message: "修改头像失败！",
                });
              });
          }
        }
      );
      console.log("field: " + field);
    },
    /**
     * upload fail
     *
     * [param] status    server api return error status, like 500
     * [param] field
     */
    cropUploadFail(status, field) {
      console.log("-------- upload fail --------");
      console.log(status);
      console.log("field: " + field);
    },
  },
};
</script>

<style scoped>
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.user-info {
  padding-left: 0;
  list-style: none;
}

.user-info li {
  border-bottom: 1px solid #f0f3f4;
  padding: 11px 0;
  font-size: 13px;
}

.user-info .user-right {
  float: right;
}
</style>